import axios from 'axios';

export type ToolResponse = { type: 'text'; content: string };

function weatherCodeToText(code: number): string {
    // 简单映射，可按需扩展
    const map: Record<number, string> = {
        0: '晴',
        1: '主要晴',
        2: '少云',
        3: '多云',
        45: '雾',
        48: '浓雾',
        51: '细雨',
        53: '小雨',
        55: '中雨',
        61: '小雨',
        63: '中雨',
        65: '大雨',
        71: '小雪',
        73: '中雪',
        75: '大雪',
        95: '雷阵雨'
    };
    return map[code] ?? `天气代码 ${code}`;
}

export const weatherTool = {
    // —— MCP / Function Calling 的工具规范 —— //
    name: 'getWeather',
    description: '根据城市名称获取当前实时天气（Open-Meteo）',
    parameters: {
        type: 'object',
        properties: {
            city: { type: 'string', description: '城市名，例如：杭州、北京、广州' },
            language: {
                type: 'string',
                description: '返回语言，默认 zh',
                enum: ['zh', 'en'],
                default: 'zh'
            }
        },
        required: ['city']
    },

    // —— 实际执行逻辑：去真实 API 拉数据 —— //
    async execute(args: { city: string; language?: 'zh' | 'en' }): Promise<ToolResponse> {
        const city = (args.city || '').trim();
        const language = args.language ?? 'zh';
        if (!city) return { type: 'text', content: '请提供要查询的城市名。' };

        // 1) 先地理编码：把城市变为经纬度
        const geo = await axios.get('https://geocoding-api.open-meteo.com/v1/search', {
            params: { name: city, count: 1, language }
        });

        if (!geo.data?.results?.length) {
            return { type: 'text', content: `未找到城市：${city}` };
        }

        const { latitude, longitude, name, country } = geo.data.results[0];

        // 2) 拉取当前天气
        const weather = await axios.get('https://api.open-meteo.com/v1/forecast', {
            params: {
                latitude,
                longitude,
                current_weather: true,
                timezone: 'auto'
            },
            timeout: 10_000
        });

        const cw = weather.data?.current_weather;
        if (!cw) return { type: 'text', content: `获取 ${city} 天气失败，请稍后再试。` };

        const text = weatherCodeToText(cw.weathercode);
        const out =
            `${name || city}${country ? '（' + country + '）' : ''} ` +
            `当前 ${cw.temperature}°C，` +
            `风速 ${cw.windspeed} km/h，` +
            `${text}。`;

        return { type: 'text', content: out };
    }
};
